package com.jsh.erp.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.jsh.erp.utils.TokenUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
//https://blog.csdn.net/l569590478/article/details/135927413
public class TenantConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor(HttpServletRequest request) {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId() {
                long tenantId = TokenUtil.parseTokenFromRequest().getTenantId();
                if (tenantId != 0L) {
                    return new LongValue(tenantId);
                } else {
                    //超管
                    return null;
                }
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            //表过滤,true忽略
            @Override
            public boolean doTableFilter(String tableName) {
                //获取开启状态
                boolean res = true;
                //todo 线程池子线程可能没有上下文获取 tenantId
                long tenantId = TokenUtil.parseTokenFromRequest().getTenantId();
                if (tenantId != 0L) {
                    // 这里可以判断是否过滤表
                    if ("material_property".equals(tableName) || "sequence".equals(tableName)
                            || "function".equals(tableName) || "platform_config".equals(tableName)
                            || "tenant".equals(tableName) || "user".equals(tableName)) {
                    } else {
                        res = false;
                    }
                }
                return res;
            }
        });

        sqlParserList.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
            @Override
            public boolean doFilter(MetaObject metaObject) {
                MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
                // 特定SQL过滤，如果在程序中，有部分SQL不需要加上租户ID的表示，需要过滤特定的sql
                //或使用@SqlParser（filter=true）
                if ("com.jsh.erp.dao.mappers.UserMapperEx.getUserByWeixinOpenId".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.dao.mappers.UserMapperEx.updateUserWithWeixinOpenId".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.dao.mappers.UserMapperEx.getUserListByUserNameOrLoginName".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.dao.mappers.UserMapperEx.disableUserByLimit".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.dao.mappers.RoleMapperEx.getRoleWithoutTenant".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.dao.mappers.LogMapperEx.insertLogWithUserId".equals(ms.getId())) {
                    return true;
                } else if ("com.jsh.erp.dao.mappers.UserBusinessMapperEx.getBasicDataByKeyIdAndType".equals(ms.getId())) {
                    return true;
                }
                return false;
            }
        });
        return paginationInterceptor;
    }


    /**
     * 性能分析拦截器，不建议生产使用
     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor(){
//        return new PerformanceInterceptor();
//    }


}
